import axios from 'axios';
import { Message } from 'element-ui';
import CONFIG_API,{EnvPreURL} from '@/api/config';
import { loading } from '@/lib/utils';
import store from 'store';
let qs = require('qs');

/**
 * tips
 */
const tips = (msg = '操作失败') => {
    Message({
        showClose: true,
        message: msg,
        type: 'error'
    });
};

let BASE_API_URL = CONFIG_API['API_URL'];
export const API_URL = BASE_API_URL;

/**
 * 提供外部获取API地址
 * @param {*} envPreURL 环境配置 参考@EnvPreURL前缀
 */
export const getApiURL = (envPreURL = 'base') => {
    let host = API_URL;
    let prefixUrl = EnvPreURL[envPreURL.toUpperCase()+'_URL'];
    return `${host}${prefixUrl}`;
}

/**
 * 根据打包命令配置，生成对应的请求环境地址
 * @param {*} config  axios配置
 */
export const getURL = (config={})=>{
    let url = `${getApiURL(config.envPreURL)}`;
    return url;
}

// 创建axios实例
const Ajax = axios.create({
    baseURL: getURL(), // api的base_url
    timeout: 30000, // 请求超时时间
    headers: {}
});

// request拦截器
Ajax.interceptors.request.use(
    config => {
        config.baseURL = getURL(config);
        let isLoading = true;
        if(config.config && config.config.loading === false){
            isLoading = false;
        }
        loading(isLoading);
        if (store.getters.userData && store.getters.userData.token) {
            config.headers['authorization'] = store.getters.userData.token; // 让每个请求携带token['token']为自定义key
        }

        if(config.method.toUpperCase() === 'GET'){
            let qsParams = qs.stringify(config.data)
            config.url = config.url + '?' + qsParams
        }

        // if(config.method.toUpperCase() === 'POST'){
        //   let form = new FormData();
        //   Object.keys(config.data).forEach(function(key){
        //     form.append(key, config.data[key]);
        //   });
        //   config.data = form
        // }

        return config;
    },
    error => {
        loading(false);
        tips('请求出错了，请重试');
        console.log(error);
        Promise.reject(error);
    }
);

// respone拦截器
Ajax.interceptors.response.use(
    response => {
        loading(false);
        let body = response.data;
        if(body && body.returnCode === 104) {
            setTimeout(()=>{
                top.vueRoot.$store.dispatch("SET_USER_DATA", null);
                top.vueRoot.$store.dispatch('SET_MENUS',null)
                top.vueRoot.$router.push({ path: '/login' });
            },1500);
            return
        }
        if(body && body.returnCode === 10000){
            return body
        }
        if(body && body.returnCode !== 10000 && body.msg) {
            tips(body.msg);
        }
        return body;
    },
    error => {
        loading(false);
        console.log(error);
        if ( error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 ) {
            tips('请求超时，请刷新重试');
        }
        return Promise.reject(error);
    }
);

export default Ajax;
